package com.ncepu.jjoj.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ncepu.jjoj.common.ErrorCode;
import com.ncepu.jjoj.exception.BusinessException;
import com.ncepu.jjoj.judge.codesandbox.CodeSandBox;
import com.ncepu.jjoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.ncepu.jjoj.judge.codesandbox.model.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * @author simon_jiang
 * @version 1.0
 */
public class RemoteCodeSandBox implements CodeSandBox {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    /**
     * 调用远程代码沙箱，得到沙箱运行结果
     * @param request
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        System.out.println("Executing code...in RemoteCodeSandBox");
        String url = "http://localhost:8121/execute";
        String jsonStr = JSONUtil.toJsonStr(request);
        String reponseStr = HttpUtil.createPost(url)
                .body(jsonStr)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .execute()
                .body();
        if(StringUtils.isBlank(reponseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remote sandbox error, message=" + reponseStr);
        }
        return JSONUtil.toBean(reponseStr, ExecuteCodeResponse.class);
    }
}
